<template>
  <div class="white-list-management">
    <!-- 统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">📊 规则统计</h2>
      <div class="stats-container">
        <StatisticCard
          label="总规则"
          :value="statistics.total.toString()"
          icon="el-icon-files"
          type="primary"
        />
        <StatisticCard
          label="启用中"
          :value="statistics.enabled.toString()"
          icon="el-icon-check-circle"
          type="success"
        />
        <StatisticCard
          label="已禁用"
          :value="statistics.disabled.toString()"
          icon="el-icon-circle-close"
          type="info"
        />
        <StatisticCard
          label="累计命中"
          :value="statistics.totalHits.toLocaleString()"
          icon="el-icon-hit"
          type="warning"
        />
        <StatisticCard
          label="今日命中"
          :value="statistics.todayHits.toString()"
          icon="el-icon-time"
          type="danger"
        />
        <StatisticCard
          label="上周新增"
          :value="statistics.lastWeekNew.toString()"
          icon="el-icon-plus-circle"
          type="primary"
        />
      </div>
    </el-card>

    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div v-if="isFilterExpanded" class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 规则列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <DynamicTable
        ref="tableRef"
        :data="ruleList"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        selection-type="multiple"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handlePageChange"
      >
        <template #table-top>
          <div class="action-bar">
            <el-button type="primary" @click="openAddModal">
              添加规则
            </el-button>
            <el-button
              type="success"
              @click="handleBatchEnable"
              :disabled="selectedRows.length === 0"
            >
              批量启用
            </el-button>
            <el-button
              type="warning"
              @click="handleBatchDisable"
              :disabled="selectedRows.length === 0"
            >
              批量禁用
            </el-button>
            <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedRows.length === 0"
            >
              批量删除
            </el-button>
            <span class="selected-count" v-if="selectedRows.length > 0">
              已选: {{ selectedRows.length }} 项
            </span>
          </div>
        </template>
        <template #status="{ row }">
          <el-switch
            v-model="row.is_enabled"
            @change="handleStatusToggle(row)"
          />
        </template>
        <template #match_condition="{ row }">
          <span v-if="!row.match_condition">-</span>
          <span v-else-if="typeof row.match_condition === 'string'">
            {{ row.match_condition }}
          </span>
          <span v-else-if="typeof row.match_condition === 'object'">
            {{ formatMatchCondition(row.match_condition) }}
          </span>
        </template>
        <template #action="{ row }">
          <el-button size="small" @click="openEditModal(row)" type="primary">
            编辑
          </el-button>
          <el-button size="small" @click="openDetailModal(row)" type="info">
            详情
          </el-button>
          <el-button size="small" @click="handleDelete(row)" type="danger">
            删除
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 添加/编辑规则弹窗 -->
    <AddEditRuleModal
      v-model="addEditVisible"
      :rule="currentRule"
      :is-edit="isEditMode"
      @save="handleSaveRule"
    />

    <!-- 规则详情弹窗 -->
    <RuleDetailModal
      v-model="detailVisible"
      :rule="currentDetailRule"
      @edit="openEditModalFromDetail"
      @change-status="handleStatusChangeFromDetail"
      @delete="handleDeleteFromDetail"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import AddEditRuleModal from "./components/AddEditRuleModal.vue";
import RuleDetailModal from "./components/RuleDetailModal.vue";
import {
  getWhitelistRules,
  getWhitelistRuleDetail,
  getWhitelistStatistics,
  createWhitelistRule,
  updateWhitelistRule,
  deleteWhitelistRule,
  toggleWhitelistRule,
  batchWhitelistRules,
} from "../../servers";

// 页面状态
const username = ref("张三");
const isFilterExpanded = ref(true);
const loading = ref(false);
const selectedRows = ref<any[]>([]);
const addEditVisible = ref(false);
const detailVisible = ref(false);
const isEditMode = ref(false);
const currentRule = ref<any>({});
const currentDetailRule = ref<any>({});

// 统计信息
const statistics = reactive({
  total: 0,
  enabled: 0,
  disabled: 0,
  totalHits: 0,
  todayHits: 0,
  lastWeekNew: 0,
});

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  rule_type: "",
  is_enabled: "",
  created_by: "",
  keyword: "",
  start_time: "",
  end_time: "",
});

// 筛选表单配置
const filterFormConfig: FormItemConfig[] = [
  {
    key: "rule_type",
    name: "规则类型",
    type: "select",
    placeholder: "请选择规则类型",
    params: { clearable: true },
    options: [
      { label: "IP地址", value: "ip" },
      { label: "IP段", value: "ip_range" },
      { label: "端口", value: "port" },
      { label: "IP+端口", value: "ip_port" },
      { label: "场景", value: "scene" },
      { label: "漏洞", value: "vuln_type" },
    ],
    col: { span: 6 },
  },
  {
    key: "is_enabled",
    name: "启用状态",
    type: "select",
    placeholder: "请选择启用状态",
    params: { clearable: true },
    options: [
      { label: "启用中", value: "true" },
      { label: "已禁用", value: "false" },
    ],
    col: { span: 6 },
  },
  {
    key: "created_by",
    name: "创建人",
    type: "input",
    placeholder: "请输入创建人",
    col: { span: 6 },
  },
  {
    key: "keyword",
    name: "关键词",
    type: "input",
    placeholder: "请输入关键词",
    col: { span: 6 },
  },
  // {
  //   key: "start_time",
  //   name: "开始时间",
  //   type: "date",
  //   placeholder: "请选择开始时间",
  //   params: {
  //     format: "YYYY-MM-DD",
  //     valueFormat: "YYYY-MM-DD",
  //     clearable: true,
  //   },
  //   col: { span: 6 },
  // },
  // {
  //   key: "end_time",
  //   name: "结束时间",
  //   type: "date",
  //   placeholder: "请选择结束时间",
  //   params: {
  //     format: "YYYY-MM-DD",
  //     valueFormat: "YYYY-MM-DD",
  //     clearable: true,
  //   },
  //   col: { span: 6 },
  // },
];

// 表格列配置
const tableColumns: TableColumn[] = [
  { label: "规则名", prop: "rule_name", minWidth: 120 },
  {
    label: "类型",
    prop: "rule_type",
    minWidth: 100,
    formatter: (row) => {
      const typeMap: Record<string, string> = {
        ip: "IP地址",
        ip_range: "IP段",
        port: "端口",
        ip_port: "IP+端口",
        scene: "场景",
        vuln_type: "漏洞",
      };
      return typeMap[row.rule_type] || row.rule_type;
    },
  },
  {
    label: "条件",
    prop: "match_condition",
    minWidth: 200,
    showOverflowTooltip: true,
    slot: "match_condition",
  },
  {
    label: "状态",
    prop: "is_enabled",
    minWidth: 100,
    slot: "status",
  },
  { label: "命中", prop: "match_count", minWidth: 80, align: "right" },
  {
    label: "创建时间",
    prop: "created_at",
    minWidth: 160,
    formatter: (row) => {
      if (!row.created_at) return "-";
      return row.created_at.replace("T", " ").substring(0, 19);
    },
  },
  { label: "创建人", prop: "created_by", minWidth: 100 },
  {
    label: "操作",
    minWidth: 200,
    fixed: "right",
    slot: "action",
  },
];

// 表格数据
const ruleList = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 表格引用
const tableRef = ref<DynamicTableInstance>();

// 格式化匹配条件
const formatMatchCondition = (condition: any): string => {
  if (!condition || typeof condition !== "object") return "-";

  const { field, operator, value } = condition;

  // 操作符映射
  const operatorMap: Record<string, string> = {
    equals: "等于",
    not_equals: "不等于",
    contains: "包含",
    not_contains: "不包含",
    starts_with: "开头为",
    ends_with: "结尾为",
    in_range: "范围内",
    not_in_range: "范围外",
    greater_than: "大于",
    less_than: "小于",
    greater_equal: "大于等于",
    less_equal: "小于等于",
  };

  const operatorText = operatorMap[operator] || operator;
  const fieldText = field || "";
  const valueText = value || "";

  if (operator === "in_range" || operator === "not_in_range") {
    // 范围类型，value 可能是数组或范围字符串
    if (Array.isArray(value)) {
      return `${fieldText} ${operatorText} [${value.join(", ")}]`;
    }
    return `${fieldText} ${operatorText} ${valueText}`;
  }

  return `${fieldText} ${operatorText} ${valueText}`;
};

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const { data } = await getWhitelistStatistics();
    if (data) {
      statistics.total = data.total_rules || 0;
      statistics.enabled = data.enabled_rules || 0;
      statistics.disabled = data.disabled_rules || 0;
      statistics.totalHits = data.total_match_count || 0;
      statistics.todayHits = data.today_match_count || 0;
      // 上周新增需要从接口返回的数据中计算，如果没有可以直接设为0
      // 或者可以根据 week_match_count 或其他字段计算
      statistics.lastWeekNew = 0; // 如果接口没有返回，可以保持为0或从其他数据计算
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
    // 统计数据获取失败不影响主流程，只打印错误
  }
};

// 获取规则列表
const fetchRuleList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    // 添加筛选条件
    if (filterForm.rule_type) {
      params.rule_type = filterForm.rule_type;
    }
    if (filterForm.is_enabled !== "") {
      params.is_enabled = filterForm.is_enabled === "true";
    }
    if (filterForm.created_by) {
      params.created_by = filterForm.created_by;
    }
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }
    if (filterForm.start_time) {
      params.start_time = `${filterForm.start_time} 00:00:00`;
    }
    if (filterForm.end_time) {
      params.end_time = `${filterForm.end_time} 23:59:59`;
    }

    const { data } = await getWhitelistRules(params);
    if (data) {
      ruleList.value = data.items || [];
      pagination.total = data.total || 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取规则列表失败");
  } finally {
    loading.value = false;
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  pagination.currentPage = 1;
  fetchRuleList();
};

const handleSearch = () => {
  pagination.currentPage = 1;
  fetchRuleList();
};

const handleExport = () => {
  ElMessage.success("Excel导出成功");
};

// 表格选择
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchRuleList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchRuleList();
};

// 弹窗控制
const openAddModal = () => {
  isEditMode.value = false;
  currentRule.value = {
    rule_name: "",
    rule_type: "ip",
    match_condition: "",
    is_enabled: true,
  };
  addEditVisible.value = true;
};

const openEditModal = (row: any) => {
  isEditMode.value = true;
  currentRule.value = { ...row };
  addEditVisible.value = true;
};

const openDetailModal = async (row: any) => {
  try {
    loading.value = true;
    const { data } = await getWhitelistRuleDetail(row.id);
    console.log(data, "datadatadatadatadata");
    if (data) {
      currentDetailRule.value = {
        ...data,
        // 补充一些显示字段
        description: data.rule_description || "无描述",
        totalHits: data.match_count || 0,
        lastHit: data.last_matched_at || "-",
      };
      detailVisible.value = true;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取规则详情失败");
  } finally {
    loading.value = false;
  }
};

const openEditModalFromDetail = (row: any) => {
  detailVisible.value = false;
  openEditModal(row);
};

// 规则操作
const handleSaveRule = async (formData: any) => {
  try {
    loading.value = true;

    // 构建 match_condition 对象
    let matchCondition: object = {};
    if (formData.type === "ip") {
      matchCondition = {
        field: "asset_ip",
        operator: "equals",
        value: formData.condition.ip || "",
      };
    } else if (formData.type === "ip_range") {
      matchCondition = {
        field: "asset_ip",
        operator: "in_range",
        value: formData.condition.ipRange || "",
      };
    } else if (formData.type === "port") {
      matchCondition = {
        field: "asset_port",
        operator: "equals",
        value: formData.condition.port || "",
      };
    } else if (formData.type === "ip_port") {
      // IP+端口可能需要特殊处理，先使用字符串格式
      matchCondition = {
        field: "asset_ip_port",
        operator: "equals",
        value: `${formData.condition.ip}:${formData.condition.port}`,
      };
    } else if (formData.type === "scene") {
      matchCondition = {
        field: "scene_type",
        operator: "equals",
        value: formData.condition.scene || "",
      };
    } else if (formData.type === "vuln_type") {
      matchCondition = {
        field: "vuln_name",
        operator:
          formData.condition.matchType === "exact" ? "equals" : "contains",
        value: formData.condition.vulnKeyword || "",
      };
    }

    // 处理适用维度
    let applicableDimensions = "";
    if (formData.applicableScenes && formData.applicableScenes.length > 0) {
      // 过滤掉 "all"
      const scenes = formData.applicableScenes.filter(
        (s: string) => s !== "all"
      );
      // 映射场景值到维度值
      const dimensionMap: Record<string, string> = {
        unreported: "unreported_asset",
        high_risk: "high_risk_asset",
        vuln_scan: "vuln_scan",
        intel_hit: "intel_hit",
        reviewed: "reviewed",
      };
      applicableDimensions = scenes
        .map((s: string) => dimensionMap[s] || s)
        .join(",");
    }

    // 处理生效时间
    let effectiveStart: string | null = null;
    let effectiveEnd: string | null = null;
    if (formData.hasExpireTime) {
      effectiveStart = formData.startTime || null;
      effectiveEnd = formData.endTime || null;
    }

    // 处理状态
    const isEnabled = formData.status === "启用中";

    if (isEditMode.value) {
      // 编辑模式
      const updateData: any = {
        rule_name: formData.name,
        rule_description: formData.description || undefined,
        match_condition: matchCondition,
        is_enabled: isEnabled,
      };

      if (applicableDimensions) {
        updateData.applicable_dimensions = applicableDimensions;
      }
      if (effectiveStart !== null) {
        updateData.effective_start = effectiveStart;
      }
      if (effectiveEnd !== null) {
        updateData.effective_end = effectiveEnd;
      }

      const result = await updateWhitelistRule(
        currentRule.value.id,
        updateData
      );
      ElMessage.success(result?.message || "规则更新成功");
    } else {
      // 新增模式
      const createData: any = {
        rule_name: formData.name,
        rule_type: formData.type,
        match_condition: matchCondition,
        is_enabled: isEnabled,
        created_by: username.value,
      };

      if (formData.description) {
        createData.rule_description = formData.description;
      }
      if (applicableDimensions) {
        createData.applicable_dimensions = applicableDimensions;
      }
      if (effectiveStart !== null) {
        createData.effective_start = effectiveStart;
      }
      if (effectiveEnd !== null) {
        createData.effective_end = effectiveEnd;
      }

      const result = await createWhitelistRule(createData);
      ElMessage.success(result?.message || "规则创建成功");
    }

    // 刷新列表和统计数据
    fetchRuleList();
    fetchStatistics();
    addEditVisible.value = false;
  } catch (error: any) {
    ElMessage.error(error?.message || "保存规则失败");
  } finally {
    loading.value = false;
  }
};

const handleBatchEnable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要启用的规则");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量启用 ${selectedRows.value.length} 条规则吗？`,
      "确认批量启用",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const ruleIds = selectedRows.value.map((row) => row.id);
    const result = await batchWhitelistRules({
      action: "enable",
      rule_ids: ruleIds,
    });

    // 处理批量操作结果
    if (result?.data) {
      const { success_count, failed_count, total_count, failed_rules } =
        result.data;
      if (failed_count === 0) {
        ElMessage.success(
          result?.message || `批量启用成功，共 ${success_count} 条规则`
        );
      } else {
        ElMessage.warning(
          `批量启用完成：成功 ${success_count} 条，失败 ${failed_count} 条`
        );
        // 如果有失败详情，显示详细错误信息
        if (failed_rules && failed_rules.length > 0) {
          const failedDetails = failed_rules
            .map((fr: any) => `规则ID ${fr.rule_id}: ${fr.reason}`)
            .join("\n");
          ElMessageBox.alert(
            `部分规则启用失败：\n${failedDetails}`,
            "启用失败详情",
            {
              type: "warning",
              confirmButtonText: "确定",
            }
          );
        }
      }
    } else {
      ElMessage.success(result?.message || "批量启用成功");
    }

    selectedRows.value = [];
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量启用失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleBatchDisable = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要禁用的规则");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量禁用 ${selectedRows.value.length} 条规则吗？`,
      "确认批量禁用",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const ruleIds = selectedRows.value.map((row) => row.id);
    const result = await batchWhitelistRules({
      action: "disable",
      rule_ids: ruleIds,
    });

    // 处理批量操作结果
    if (result?.data) {
      const { success_count, failed_count, total_count, failed_rules } =
        result.data;
      if (failed_count === 0) {
        ElMessage.success(
          result?.message || `批量禁用成功，共 ${success_count} 条规则`
        );
      } else {
        ElMessage.warning(
          `批量禁用完成：成功 ${success_count} 条，失败 ${failed_count} 条`
        );
        // 如果有失败详情，显示详细错误信息
        if (failed_rules && failed_rules.length > 0) {
          const failedDetails = failed_rules
            .map((fr: any) => `规则ID ${fr.rule_id}: ${fr.reason}`)
            .join("\n");
          ElMessageBox.alert(
            `部分规则禁用失败：\n${failedDetails}`,
            "禁用失败详情",
            {
              type: "warning",
              confirmButtonText: "确定",
            }
          );
        }
      }
    } else {
      ElMessage.success(result?.message || "批量禁用成功");
    }

    selectedRows.value = [];
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量禁用失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的规则");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要批量删除 ${selectedRows.value.length} 条规则吗？此操作不可恢复！`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: false,
      }
    );

    loading.value = true;
    const ruleIds = selectedRows.value.map((row) => row.id);
    const result = await batchWhitelistRules({
      action: "delete",
      rule_ids: ruleIds,
    });

    // 处理批量操作结果
    if (result?.data) {
      const { success_count, failed_count, total_count, failed_rules } =
        result.data;
      if (failed_count === 0) {
        ElMessage.success(
          result?.message || `批量删除成功，共 ${success_count} 条规则`
        );
      } else {
        ElMessage.warning(
          `批量删除完成：成功 ${success_count} 条，失败 ${failed_count} 条`
        );
        // 如果有失败详情，可以在这里显示
        if (failed_rules && failed_rules.length > 0) {
          const failedDetails = failed_rules
            .map((fr: any) => `规则ID ${fr.rule_id}: ${fr.reason}`)
            .join("\n");
          ElMessageBox.alert(
            `部分规则删除失败：\n${failedDetails}`,
            "删除失败详情",
            {
              type: "warning",
              confirmButtonText: "确定",
            }
          );
        }
      }
    } else {
      ElMessage.success(result?.message || "批量删除成功");
    }

    selectedRows.value = [];
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "批量删除失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则【${row.rule_name}】吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await deleteWhitelistRule(row.id);
    ElMessage.success(result?.message || "规则删除成功");
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "删除规则失败");
    }
  } finally {
    loading.value = false;
  }
};

// 状态切换处理
const handleStatusToggle = async (row: any) => {
  const newStatus = row.is_enabled;
  const actionText = newStatus ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}规则【${row.rule_name}】吗？`,
      `确认${actionText}`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await toggleWhitelistRule(row.id, newStatus);
    ElMessage.success(result?.message || `规则已${actionText}`);
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    // 如果用户取消，回滚状态
    if (error === "cancel") {
      row.is_enabled = !newStatus;
    } else {
      // 如果接口调用失败，也回滚状态
      row.is_enabled = !newStatus;
      ElMessage.error(error?.message || `${actionText}规则失败`);
    }
  } finally {
    loading.value = false;
  }
};

const handleStatusChangeFromDetail = async (row: any, status: string) => {
  const isEnabled = status === "启用中";
  const actionText = isEnabled ? "启用" : "禁用";

  try {
    await ElMessageBox.confirm(
      `确定要${actionText}规则【${row.rule_name}】吗？`,
      `确认${actionText}`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await toggleWhitelistRule(row.id, isEnabled);
    currentDetailRule.value.is_enabled = isEnabled;
    ElMessage.success(result?.message || `规则已${actionText}`);
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || `${actionText}规则失败`);
    }
  } finally {
    loading.value = false;
  }
};

const handleDeleteFromDetail = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除规则【${row.rule_name}】吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    const result = await deleteWhitelistRule(row.id);
    detailVisible.value = false;
    ElMessage.success(result?.message || "规则删除成功");
    fetchRuleList();
    fetchStatistics();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "删除规则失败");
    }
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchStatistics();
  fetchRuleList();
});
</script>

<style scoped lang="scss">
.white-list-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .navbar-card {
    margin-bottom: 20px;
    border-radius: 8px;

    .navbar-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .page-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
        color: #333;
      }

      .user-info {
        color: #666;
        font-size: 14px;
      }
    }
  }

  .stats-card,
  .filter-card,
  .action-bar-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .filter-content {
    padding: 5px 0;
  }

  .filter-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;

    .action-btn {
      margin-right: 10px;
    }

    .export-btn {
      margin-left: auto;
    }
  }

  .action-bar {
    display: flex;
    align-items: center;
    gap: 10px;

    .selected-count {
      margin-left: auto;
      color: #666;
      font-size: 14px;
    }
  }
}
</style>
